package cn.donting.web.desktop.sys.controller;

import cn.donting.web.desktop.core.app.AppManager;
import cn.donting.web.desktop.core.domain.ResponseEntity;
import cn.donting.web.desktop.core.domain.Wap;
import cn.donting.web.desktop.core.entity.AppInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author donting
 * 2021-06-06 下午5:47
 */
@RestController("/sys/app/manger")
@Slf4j
public class AppMangerController {

    @Autowired
    @Qualifier("appManager")
    private AppManager appManager;
    @Autowired
    private ObjectMapper objectMapper;

    @PostMapping("/install")
    public ResponseEntity install(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return ResponseEntity.error(500, "上传的文件为空");
        }
        AppInfo install = appManager.install(file.getBytes());
        ResponseEntity ok = ResponseEntity.ok(install);
        return ok;
    }

    @GetMapping("/apps")
    public ResponseEntity<List<AppInfo>> apps(){
        List<AppInfo> installApps = appManager.getInstallApps();
        return ResponseEntity.ok(installApps);
    }
    @GetMapping("/uninstall")
    public ResponseEntity uninstall(Long appId){
        appManager.unInstall(appId);
        return ResponseEntity.ok(null);
    }
    @PostMapping("/wap")
    public ResponseEntity creatWap(Long appId,String filePath){
        try {
            Wap wap = appManager.creatWap(appId);
            if (!filePath.endsWith(".wap")) {
                filePath += ".wap";
            }
            File file = new File(filePath);
            if (file.exists()) {
                return ResponseEntity.error(500, "文件已存在：" + filePath);
            }
            file.createNewFile();
            objectMapper.writeValue(file, wap);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return ResponseEntity.error(500,e.getMessage());

        }
        return ResponseEntity.ok(filePath);
    }

}
